<?php
class URIMapping {
	
	private static $delimiter = "/";
	private static $wildcard = '*';
	
	public static $root = '/';
	
	private $children = array();
	private $resource = NULL;
	private $currentURIComponent = NULL;
	
	private $logger;
	
	public function __construct($uriComponent) {
		
		$this->currentURIComponent = $uriComponent;
		$this->logger = LoggerFactory::getLogger('URIMapping_' . $uriComponent);
	}
	
	private function explodeURI($uri) {
		
		if (strlen($uri) == 0) {
			return array();
		}

		return preg_split('#/#', $uri, -1, PREG_SPLIT_NO_EMPTY);
	}
	
	public function getResource($uri) {
		
		if (is_string($uri)) {
			$uri = $this->explodeURI($uri);
		}
		
		$resource = NULL;
		$uriComponent = $uri[0];
		$child = $this->children[$uriComponent];
		
		if (count($uri) == 0) {
			$resource = $this->resource;
			
		} else if ($child != NULL) {
			$childURI = array_slice($uri, 1);
			$resource = $child->getResource($childURI);
			
		} 
		
		if ($resource == null) {
			$child = $this->children[self::$wildcard];
			$resource = $child == NULL ? NULL : $child->getResource(self::$root);
		}
		
		return $resource;
	}
	
	public function addResource($uri, Resource $resource) {
		
		if (is_string($uri)) {
			$uri = $this->explodeURI($uri);
		}

		if (count($uri) == 0) {
			$this->logger->debug('Adding resource to ' . $this->currentURIComponent);
			$this->resource = $resource;
			return;
		}
		
		$uriComponent = $uri[0];
		$child = $this->children[$uriComponent]; 
		if ($child == NULL) {
			$child = new URIMapping($uriComponent);
			$this->children[$uriComponent] = $child;
		}
		
		$childURI = array_slice($uri, 1);
		$child->addResource($childURI, $resource);
	}
}
?>